
import os
from amplitude.dict import Dict
from jinja2 import Environment, FileSystemLoader, FileSystemBytecodeCache

class Context(Dict):

    def __init__(self, engine='jinja2', template_dirs=[], cache_dir=None, auto_reload=False, **args):
        Dict.__init__(self, engine=engine, template_dirs=template_dirs, cache_dir=cache_dir, auto_reload=auto_reload, **args)
        if engine=='jinja2':
            self.loader = self.loader or FileSystemLoader(template_dirs)
            if cache_dir is not None:
                if not os.path.isdir(cache_dir): os.makedirs(cache_dir)
                self.cache = self.cache or FileSystemBytecodeCache(directory=cache_dir)
            self.env = self.env or Environment(loader=self.loader, bytecode_cache=self.cache, auto_reload=auto_reload)

    def load_template(self, name):
        "returns a template object that has a render(**args) method."
        if self.engine=='jinja2':
            return self.env.get_template(name)


class Template(Dict):

    def __init__(self, name, **args):
        self.context = Context(**args)
        self.template = self.context.load_template(name)

    def render(self, **args):
        self.template.render(**args)